package lendingbooks.utils;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;



public class ServiceManager {

	public static enum SERVICE {SEARCH_BY_ISBN,MY_LIBRARY, LOGIN_FACEBOOK};
	
	@SuppressWarnings("serial")
	private static final Map<SERVICE, String> SERVICES_MAP = 
			Collections.unmodifiableMap(new HashMap<SERVICE, String>() {{ 
			    put(SERVICE.SEARCH_BY_ISBN, "http://lending-books.appspot.com/services/book.search_by_isbn.jsp");
			    put(SERVICE.MY_LIBRARY, "http://lending-books.appspot.com/services/copy.find.user.jsp");
			    put(SERVICE.LOGIN_FACEBOOK, "http://lending-books.appspot.com/services/login.facebook.jsp");
			    
			}});
	
	public String call(SERVICE p_service, HashMap<String,String> p_params) throws ServiceCallException{
		String response = null;
		try{
		DefaultHttpClient httpClient = new DefaultHttpClient();
		URI uri = new URI(SERVICES_MAP.get(p_service));
		HttpPost httpPost = new HttpPost(uri);
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for(Entry<String,String> entry: p_params.entrySet()){			
			pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}		
		httpPost.setEntity(new UrlEncodedFormEntity(pairs));
		HttpResponse httpResponse = httpClient.execute(httpPost);
		HttpEntity httpEntity = httpResponse.getEntity();
		response = EntityUtils.toString( httpEntity );
		}catch(Exception ex){
			throw new ServiceCallException();
		}
		return response;
	}
}
